<?php
namespace Core\Service\Image;
use Core\Helper\CommonHelper;
use WideImage;

include_once("Wideimage/WideImage.php");
class ImageWide implements ImageInterface
{

    /**
     * @param $imagePath
     * @param $width
     * @param $height
     * @param $prefix_name
     * @param bool $isUpdate
     * @usage use $isUpdate = true if just want to transform image but still keeping image old name
     * @return string
     */

    public function transformImageBlock($imagePath, $width, $height,$prefix_name, $isUpdate = false)
    {
        $image = WideImage::load($imagePath);

        if(!$isUpdate){
            $asciiPrefixName = CommonHelper::vietnameseToASCII($prefix_name);
            $fileInfo = pathinfo($imagePath);
            $newFileName = substr($fileInfo['filename'].'_'.$asciiPrefixName, 0, 255);

            $newFilePath = $fileInfo['dirname'].'/'.$newFileName.'.'.$fileInfo['extension'];

            //create new file
            $image->resize($width, $height, 'outside')->crop("center", "center", $width, $height)
                ->saveToFile($newFilePath);
            //create new thumb
            $thumbFile = substr($imagePath, 0, strlen(CORE_ASSET_CMS_DIRECTORY)).'/_thumbs'.
                substr($imagePath,  strlen(CORE_ASSET_CMS_DIRECTORY));

            $thumbFileInfo = pathinfo($thumbFile);
            $newThumbFileName = substr($thumbFileInfo['filename'].'_'.$asciiPrefixName, 0, 255);
            $newThumbFilePath = $thumbFileInfo['dirname'].'/'.$newThumbFileName.'.'.$thumbFileInfo['extension'];
            $image = WideImage::load($imagePath);
            $image->resize(90, 90, 'outside')->crop("center", "center", 90,90)
                ->saveToFile($newThumbFilePath);
            return $newFilePath;
        }
        else{
            $image->resize($width, $height, 'outside')->crop("center", "center", $width, $height)
                ->saveToFile($imagePath);
            //do you need to regenerate thumb file? write here.
            return $imagePath;
        }

    }
}
